package com.cy.store.controller;

import com.cy.store.entity.Address;
import com.cy.store.service.IAddressService;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("/address")
@RestController
public class AddressController extends BaseController{
    @Autowired
    private IAddressService addressService;

    @RequestMapping("/add_address")
    public JsonResult<Void> addAddress(HttpSession session, Address address){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        addressService.addAddress(uid,username,address);
        return new JsonResult<>(Ok);
    }

    @RequestMapping(value = {"","/"})
    public JsonResult<List<Address>> addressList(HttpSession session){
        Integer uid = getUidFromSession(session);
        List<Address> data = addressService.findByUid(uid);
        return new JsonResult<>(Ok,data);
    }

    @RequestMapping("{aid}/change_default")
    public JsonResult<Void> changeDefault(@PathVariable("aid") Integer aid, HttpSession session){
        addressService.changeDefault(getUidFromSession(session),
                                     aid,
                                     getUsernameFromSession(session));
        return new JsonResult<>(Ok);
    }
    @RequestMapping("{aid}/delete_address")
    public JsonResult<Void> deleteAddress(HttpSession session,@PathVariable("aid") Integer aid){
        addressService.deleteAddress(getUidFromSession(session),
                                     aid,
                                     getUsernameFromSession(session));
        return new JsonResult<>(Ok);
    }
}
